package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.Subject;
import cn.ibizlab.businesscentral.core.base.service.ISubjectService;
import cn.ibizlab.businesscentral.core.base.filter.SubjectSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"主题" })
@RestController("CentralApi-subject")
@RequestMapping("")
public class SubjectResource {

    @Autowired
    public ISubjectService subjectService;

    @Autowired
    @Lazy
    public SubjectMapping subjectMapping;

    @PreAuthorize("hasPermission(this.subjectMapping.toDomain(#subjectdto),'iBizBusinessCentral-Subject-Create')")
    @ApiOperation(value = "新建主题", tags = {"主题" },  notes = "新建主题")
	@RequestMapping(method = RequestMethod.POST, value = "/subjects")
    public ResponseEntity<SubjectDTO> create(@RequestBody SubjectDTO subjectdto) {
        Subject domain = subjectMapping.toDomain(subjectdto);
		subjectService.create(domain);
        SubjectDTO dto = subjectMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.subjectMapping.toDomain(#subjectdtos),'iBizBusinessCentral-Subject-Create')")
    @ApiOperation(value = "批量新建主题", tags = {"主题" },  notes = "批量新建主题")
	@RequestMapping(method = RequestMethod.POST, value = "/subjects/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<SubjectDTO> subjectdtos) {
        subjectService.createBatch(subjectMapping.toDomain(subjectdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "subject" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.subjectService.get(#subject_id),'iBizBusinessCentral-Subject-Update')")
    @ApiOperation(value = "更新主题", tags = {"主题" },  notes = "更新主题")
	@RequestMapping(method = RequestMethod.PUT, value = "/subjects/{subject_id}")
    public ResponseEntity<SubjectDTO> update(@PathVariable("subject_id") String subject_id, @RequestBody SubjectDTO subjectdto) {
		Subject domain  = subjectMapping.toDomain(subjectdto);
        domain .setSubjectid(subject_id);
		subjectService.update(domain );
		SubjectDTO dto = subjectMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.subjectService.getSubjectByEntities(this.subjectMapping.toDomain(#subjectdtos)),'iBizBusinessCentral-Subject-Update')")
    @ApiOperation(value = "批量更新主题", tags = {"主题" },  notes = "批量更新主题")
	@RequestMapping(method = RequestMethod.PUT, value = "/subjects/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<SubjectDTO> subjectdtos) {
        subjectService.updateBatch(subjectMapping.toDomain(subjectdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.subjectService.get(#subject_id),'iBizBusinessCentral-Subject-Remove')")
    @ApiOperation(value = "删除主题", tags = {"主题" },  notes = "删除主题")
	@RequestMapping(method = RequestMethod.DELETE, value = "/subjects/{subject_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("subject_id") String subject_id) {
         return ResponseEntity.status(HttpStatus.OK).body(subjectService.remove(subject_id));
    }

    @PreAuthorize("hasPermission(this.subjectService.getSubjectByIds(#ids),'iBizBusinessCentral-Subject-Remove')")
    @ApiOperation(value = "批量删除主题", tags = {"主题" },  notes = "批量删除主题")
	@RequestMapping(method = RequestMethod.DELETE, value = "/subjects/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        subjectService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.subjectMapping.toDomain(returnObject.body),'iBizBusinessCentral-Subject-Get')")
    @ApiOperation(value = "获取主题", tags = {"主题" },  notes = "获取主题")
	@RequestMapping(method = RequestMethod.GET, value = "/subjects/{subject_id}")
    public ResponseEntity<SubjectDTO> get(@PathVariable("subject_id") String subject_id) {
        Subject domain = subjectService.get(subject_id);
        SubjectDTO dto = subjectMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取主题草稿", tags = {"主题" },  notes = "获取主题草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/subjects/getdraft")
    public ResponseEntity<SubjectDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(subjectMapping.toDto(subjectService.getDraft(new Subject())));
    }

    @ApiOperation(value = "检查主题", tags = {"主题" },  notes = "检查主题")
	@RequestMapping(method = RequestMethod.POST, value = "/subjects/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody SubjectDTO subjectdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(subjectService.checkKey(subjectMapping.toDomain(subjectdto)));
    }

    @PreAuthorize("hasPermission(this.subjectMapping.toDomain(#subjectdto),'iBizBusinessCentral-Subject-Save')")
    @ApiOperation(value = "保存主题", tags = {"主题" },  notes = "保存主题")
	@RequestMapping(method = RequestMethod.POST, value = "/subjects/save")
    public ResponseEntity<Boolean> save(@RequestBody SubjectDTO subjectdto) {
        return ResponseEntity.status(HttpStatus.OK).body(subjectService.save(subjectMapping.toDomain(subjectdto)));
    }

    @PreAuthorize("hasPermission(this.subjectMapping.toDomain(#subjectdtos),'iBizBusinessCentral-Subject-Save')")
    @ApiOperation(value = "批量保存主题", tags = {"主题" },  notes = "批量保存主题")
	@RequestMapping(method = RequestMethod.POST, value = "/subjects/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<SubjectDTO> subjectdtos) {
        subjectService.saveBatch(subjectMapping.toDomain(subjectdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Subject-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Subject-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"主题" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/subjects/fetchdefault")
	public ResponseEntity<List<SubjectDTO>> fetchDefault(SubjectSearchContext context) {
        Page<Subject> domains = subjectService.searchDefault(context) ;
        List<SubjectDTO> list = subjectMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Subject-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Subject-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"主题" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/subjects/searchdefault")
	public ResponseEntity<Page<SubjectDTO>> searchDefault(@RequestBody SubjectSearchContext context) {
        Page<Subject> domains = subjectService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(subjectMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

